const loginDao = require('../dao/login');
const verificeDao = require('../dao/verifice');

const config = require('../config');

const { verifyJwtToken, createUserJwtToken } = require('../util/server_jwt');

const loginService = {
    // 登录卡密接口
    async cardkeyLogin(cardkey, nowDate) {
        let result;
        let token_time = 720;
        try {
            result = await loginDao.cardkeyLogin(cardkey);
            if (result.length) {
                // 检查卡密是否过期
                let endAt = result[0].endAt;
                if (endAt) {
                    let endAtObj = new Date(endAt);
                    let endAtTime = endAtObj.getTime();
                    let nowTime = nowDate.getTime();
                    if (endAtTime < nowTime) {
                        return { code: 401, msg: "卡密过期", data: null };
                    }
                    let time = parseInt((endAtTime - nowTime) / 3600000);
                    token_time = time < token_time ? time : token_time;
                }
                // 登录成功
                let url = result[0].url;
                let uid = result[0].id;
                let userTypeId = result[0].userTypeId;
                let payload = { uid, userTypeId };
                let token = await createUserJwtToken(payload, { expiresIn: `${token_time}h` });
                await loginDao.userLoginInc(uid);  // 登录次数 加1
                result = { code: 200, msg: '登录成功', data: { token, url } };
            } else {
                result = { code: 401, msg: "卡密错误", data: null };
            }
        } catch (err) {
            result = { code: 500, msg: "服务器错误", data: null };
        }
        return result;
    }
};

module.exports = loginService;
